package cn.chiship.sdk.framework.util;

import cn.chiship.sdk.core.exception.custom.SystemErrorException;
import cn.chiship.sdk.core.util.FileUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author lijian
 */
public class File2Util extends FileUtil {

	/**
	 * 读取文件
	 * @param file 文件
	 * @return String
	 */
	public static String readResourceFile(String file) {
		try {
			Resource resource = new ClassPathResource(file);
			InputStream is = resource.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String s;
			StringBuilder sb = new StringBuilder();
			while ((s = br.readLine()) != null) {
				sb.append(s + "\n");
			}
			br.close();
			isr.close();
			is.close();
			return sb.toString();
		}
		catch (Exception e) {
			throw new SystemErrorException("读取文件错误" + file);
		}
	}

	/**
	 * 读取文件
	 * @param file 文件
	 * @return InputStream
	 */
	public static InputStream readResourceIs(String file) {
		try {
			Resource resource = new ClassPathResource(file);
			return resource.getInputStream();
		}
		catch (Exception e) {
			throw new SystemErrorException("读取文件错误" + file);
		}
	}

	/**
	 * 读取文件
	 * @param file 文件
	 * @return byte[]
	 */
	public static byte[] readResource(String file) {
		try {
			Resource resource = new ClassPathResource(file);
			InputStream is = resource.getInputStream();
			byte[] bytes = IOUtils.toByteArray(is);
			is.close();
			return bytes;
		}
		catch (Exception e) {
			throw new SystemErrorException("读取文件错误" + file);
		}
	}

}
